import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  data: {
    countDownVisible: false,
    mobile: '15215525991',
    code: '',
  },
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    code: [
      { required: true, message: '请填写验证码!!!!!' },
      { pattern: /^\d{6}$/, message: '请填写正确的验证码!' },
    ],
  },
  // onLoad({ redirectUrl }) {
  //   this.redirectUrl = redirectUrl
  // },
  onLoad(options) {
    console.log(options)
    this.redirectUrl = options.redirectUrl
  },

  countDownChange(ev) {
    console.log(ev)
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  async getSMSCode() {
    let { valid, message } = this.validate('mobile')
    console.log(valid)
    if (!valid) return wx.utils.toast(message)
    this.setData({
      countDownVisible: true,
    })
    let { code } = await wx.http.get('/code', { mobile: this.data.mobile })
    console.log(code)
    this.setData({ code })
  },
  async submitForm() {
    let isPass = this.validate()
    if (!isPass) return
    let res = await wx.http.post('/login', {
      code: this.data.code,
      mobile: this.data.mobile,
    })
    console.log(res)
    wx.utils.toast('登录成功', 'success')
    // 存储token
    const app = getApp()
    app.setToken('token', res.token)
    app.setToken('refreshToken', res.refreshToken)
    // 跳转页面
    console.log(this.redirectUrl)
    wx.redirectTo({
      url: '/' + this.redirectUrl,
    })
  },
})
